package pers.mingshan.thread;

/**
 * @author hanjuntao
 * @date 2025/6/25 0025
 */
public class Print100_2 {
    private static int count = 0;
    private static final Object lock = new Object();

    public static void main(String[] args) {
        Thread evenThread = new Thread(() -> {
            while (count <= 100) {
                synchronized (lock) {
                    // 检查是否为偶数且未超限
                    if (count % 2 == 0 && count <= 100) {
                        System.out.println(Thread.currentThread().getName() + ": " + count);
                        count++;
                        lock.notify(); // 唤醒另一个线程
                    } else {
                        try {
                            lock.wait(); // 让出锁并等待
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }, "Even-Thread");

        Thread oddThread = new Thread(() -> {
            while (count <= 100) {
                synchronized (lock) {
                    // 检查是否为奇数且未超限
                    if (count % 2 == 1 && count <= 100) {
                        System.out.println(Thread.currentThread().getName() + ": " + count);
                        count++;
                        lock.notify(); // 唤醒另一个线程
                    } else {
                        try {
                            lock.wait(); // 让出锁并等待
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }, "Odd-Thread");

        evenThread.start();
        oddThread.start();
    }
}
